package top.yokey.shopai.zcom.voice;

import android.app.Activity;
import android.widget.TextView;

import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

@SuppressWarnings("ALL")
public class XFVoiceDialog {

    private static volatile XFVoiceDialog instance = null;

    public static XFVoiceDialog get() {

        if (instance == null) {
            synchronized (XFVoiceDialog.class) {
                if (instance == null) {
                    instance = new XFVoiceDialog();
                }
            }
        }
        return instance;

    }

    public void show(Activity activity, XFVoiceListener voiceListener) {

        RecognizerDialog recognizerDialog = new RecognizerDialog(activity, null);
        recognizerDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        recognizerDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        recognizerDialog.setParameter(SpeechConstant.VAD_BOS, "1500");
        recognizerDialog.setParameter(SpeechConstant.VAD_EOS, "1500");
        recognizerDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean isLast) {
                if (!isLast) {
                    String result = "";
                    try {
                        JSONArray jsonArray = new JSONObject(recognizerResult.getResultString()).getJSONArray("ws");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String cw = jsonArray.getJSONObject(i).getString("cw");
                            String w = new JSONArray(cw).getJSONObject(0).getString("w");
                            result += w;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (voiceListener != null) {
                        voiceListener.onResult(result);
                        recognizerDialog.dismiss();
                    }
                }
            }

            @Override
            public void onError(SpeechError speechError) {

            }
        });
        recognizerDialog.show();
        TextView textView = recognizerDialog.getWindow().getDecorView().findViewWithTag("textlink");
        textView.setText("");

    }

}
